import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { aiChater } from "@/api/chat";
import { CODE } from "@/api/constants";
import { now_seconds } from "@/utils/time";
import { v4 as uuidv4 } from 'uuid';
import useChatListStore from "@/stores/chatList";
import { INVALID_CHAT_ID } from "./chatList";
import { list_chat_msgs } from "../api/chat";

export const MsgType = Object.freeze({
    USER: 'user',
    OTHER: 'ai'
})

export const INVALID_MSG_ID = "";

const useChatStore = defineStore('current-chat', () => {
    const messages = ref([])
    const createDia = (msgId, content, role, dialogId) => {
        return {
            id: msgId,
            content: content,
            role: role,
            chatAt: now_seconds(),
            dialogID: dialogId,
            requestId: uuidv4(),
        }
    }
    const pushMsg = (msg) => {
        messages.value.push(msg)
    }

    const canChat = computed(() => {
        return useChatListStore().isSelectActiveDia
    })

    const onMessage = (data, onError, dia) => {
        if (data.code != CODE.OK) {
            onError(data)
            return
        }
        dia.id = data.data.dialogID
        if (messages.value.length < 0) {
            throw new Error('非法修改聊天记录: 没有聊天记录')
        }
        messages.value[messages.value.length - 1].content = data.data.content
    }

    const send = async (content, onFinish, onError) => {
        const dia = useChatListStore().activeChatDia
        useChatListStore().topDia(dia)
        aiChater.onMessage = (data) => { onMessage(data, onError, dia) }
        aiChater.onFinish = onFinish
        aiChater.onError = onError
        const userMsg =  createDia(INVALID_MSG_ID, content, MsgType.USER, dia.id)
        pushMsg(userMsg)
        const aiMsg =  createDia(INVALID_MSG_ID, "", MsgType.OTHER, dia.id)
        pushMsg(aiMsg)
        await aiChater.send({
            chatMsg: userMsg,
            chatDialog: dia,
            isNew: dia.id === INVALID_CHAT_ID,
        })
    }

    const abort = () => {
        aiChater.abort()
    }

    // 聊天记录列表获取
    const defaultOnList = (resp) => {
        console.info(resp)
    }
    let onList = defaultOnList
    const registerOnList = (callback) => {
        onList = callback
    }
    const unregisterOnList = () => {
        onList = defaultOnList
    }
    watch(
        [
            () => useChatListStore().activeChatDia, 
            () => useChatListStore().isSelectActiveDia
        ],
        async ([newChatDia, newIsActive], [oldChatDia, oldIsActive]) => {
            if (newChatDia !== oldChatDia) {
                abort() // 立即中断当前会话
            }
            if (!newIsActive || newChatDia.id === INVALID_CHAT_ID) {
                messages.value = []
                return
            }
            const resp = await list_chat_msgs({ dialogId: newChatDia.id })
            onList && onList(resp)
            messages.value = resp.data.msgs
        }
    )

    return { messages, send, canChat, abort, registerOnList, unregisterOnList }
})

export default useChatStore;